import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { request, useRequest } from '@umijs/max';
import { Button } from 'antd';
import React, { useRef } from 'react';

type TagRecord = {
  record: {
    id: number;
    type: 'Kit' | 'Template';
    label: string;
    name: string;
    description: string;
    createAt: string;
  };
  onFinish: () => void;
  children?: React.ReactNode;
};

const AddTag: React.FC<Partial<TagRecord>> = ({
  children,
  record,
  ...props
}) => {
  const { run: createTag } = useRequest(
    (data) => {
      return request('/api/labels', {
        method: 'POST',
        data,
      });
    },
    {
      manual: true,
    },
  );

  const { run: updateTag } = useRequest(
    (data) => {
      return request(`/api/labels/${data.id}`, {
        method: 'PATCH',
        data,
      });
    },
    {
      manual: true,
    },
  );

  return (
    <ModalForm
      title={record ? '编辑' : '新增'}
      initialValues={{ ...record }}
      trigger={children as unknown as JSX.Element}
      onFinish={async (data) => {
        if (record?.id) {
          await updateTag(data);
        } else {
          await createTag(data);
        }

        if (props?.onFinish) {
          props?.onFinish();
        }
        return true;
      }}
    >
      <ProFormText name="id" label="标签ID" hidden />
      <ProFormSelect
        name="type"
        label="标签类型"
        fieldProps={{
          options: [
            {
              label: '套件',
              value: 'Kit',
            },
            {
              label: '模板',
              value: 'Template',
            },
          ],
        }}
        rules={[
          {
            required: true,
            message: '请输入Tag类型',
          },
        ]}
      />
      <ProFormText
        name="label"
        label="标签名称"
        rules={[
          {
            required: true,
            message: '请输入标签名称',
          },
        ]}
      />
      <ProFormText
        name="name"
        label="标签属性"
        rules={[
          {
            required: true,
            message: '请输入标签属性',
          },
        ]}
      />
      <ProFormText name="description" label="标签描述" />
    </ModalForm>
  );
};

const Tag = () => {
  const acitonRef = useRef<ActionType>();
  const {
    run: getList,
    loading,
    data,
  } = useRequest(
    (params) => {
      return request('/api/labels', {
        method: 'GET',
        params,
      });
    },
    {
      manual: true,
    },
  );

  const columns: ProColumns<TagRecord['record']>[] = [
    {
      title: '标签类型',
      dataIndex: 'type',
      renderText(text: TagRecord['record']['type']) {
        return text === 'Kit' ? '套件' : '模板';
      },
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '套件',
            value: 'Kit',
          },
          {
            label: '模板',
            value: 'Template',
          },
        ],
      },
    },
    {
      title: '标签名称',
      dataIndex: 'label',
    },
    {
      title: '标签属性',
      dataIndex: 'name',
    },
    {
      title: '标签描述',
      dataIndex: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => (
        <>
          <AddTag record={record} onFinish={() => acitonRef.current?.reload()}>
            <Button type="text">编辑</Button>
          </AddTag>
          <Button type="text">删除</Button>
        </>
      ),
    },
  ];

  return (
    <ProTable
      actionRef={acitonRef}
      loading={loading}
      columns={columns}
      request={async (params) => {
        const { current: pageNum, ...rest } = params;

        return await getList({
          pageNum,
          ...rest,
        });
      }}
      dataSource={data?.rows}
      toolBarRender={() => [
        <AddTag key={'add'} onFinish={() => acitonRef.current?.reload()}>
          <Button type="primary">添加</Button>
        </AddTag>,
      ]}
    />
  );
};

export default Tag;
